/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(!head)
            return nullptr;
        //链表复制
       struct Node* cur = head;
       struct Node* next = head;
        while(cur){
           struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
            if(!newnode)
                return nullptr;
            next = cur->next;
            cur->next = newnode;
            newnode->next = next;
            newnode->val = cur->val;
            cur = next; 
        }
        struct Node* newHead = head->next;
        //随机指针的赋值
        cur = head;
        while(cur){
            next = cur->next;
            if(!cur->random)
                next->random = cur->random;
            else
                next->random = cur->random->next;
            cur = next->next;
        }    
        //链表恢复排列      
        cur = head;
        while(cur->next){
            next = cur->next;
            cur->next = next->next;
            cur = next;
        }
        return newHead;
    }
};